﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace WH_Mngr
{
    public partial class Form1 : Form
    {
        const string CFG_DATA_PATH = "data_path";
        public string m_cfgfilePath = Environment.CurrentDirectory + @"\Config.bin";
        public string m_data_path = "";
        public string m_log = "";


        public class Meterial_DATA
        {
            public int NO;                  //序号
            public string meterial_No;      //物料编号
            public DateTime date;           //日期
            public int checkin_qty;         //入库数量
            public int checkout_qty;        //出库数量
            public int stock_qty;           //库存
        }


        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            read_sys_config();
            this.dateTimePicker_date.Format = DateTimePickerFormat.Custom;
           

        }

        private void read_sys_config()
        {
            if (File.Exists(m_cfgfilePath))
            {
                FileStream fs=new FileStream(m_cfgfilePath, FileMode.Open, FileAccess.Read);
                StreamReader sr=new StreamReader(fs);

                string read_str = sr.ReadLine();
                while (read_str != null)
                {
                    if (read_str.IndexOf(CFG_DATA_PATH) >= 0)
                    {
                        m_data_path = read_str.Substring(read_str.LastIndexOf("=") + 1);
                    }
                    read_str = sr.ReadLine();
                }

                sr.Close();
                fs.Close();
            }
        }

        private void 配置数据路径ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_data_path form_Data_Path = new Form_data_path();
            form_Data_Path.get_data_path(m_data_path);
            form_Data_Path.m_getPathHandler += new GetPathHandler(get_data_path);
            form_Data_Path.ShowDialog();
        }

        private void get_data_path(string path)
        {
            m_data_path = path;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //保存设置
            save_cfg_file();

            //存储日志
            save_log();
        }

        private void save_log()
        {
            string log_path= Environment.CurrentDirectory + @"\Log";
            if (!Directory.Exists(log_path))
            {
                var d=Directory.CreateDirectory(log_path);
            }

            string file_path = log_path + @"\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            FileStream fs = new FileStream(file_path, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);

            sw.WriteLine(m_log);

            sw.Close();
            fs.Close();
        }


        private void save_cfg_file()
        {
            FileStream fs = new FileStream(m_cfgfilePath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);

            sw.WriteLine(CFG_DATA_PATH + "=" + m_data_path);

            sw.Close();
            fs.Close();
        }

        private void button_ok_Click(object sender, EventArgs e)
        {
            if (m_data_path == "")
            {
                MessageBox.Show("请在帮助中选择数据路径");
                return;
            }

            string meterial_No = this.textBox_meterial_No.Text;
            if (meterial_No == "")
            {
                MessageBox.Show("物料编号为空");
                return;
            }

            string path = m_data_path + @"\" + meterial_No + ".csv";
            //根据物料编号，写入文件
            if (File.Exists(path))  //文件存在，就在后面接着写
            {
                //获取当前的数据
                //List<Meterial_DATA> list_meterial = new List<Meterial_DATA>();

                FileStream fs = new FileStream(path, FileMode.Open,FileAccess.ReadWrite);
                StreamReader sr = new StreamReader(fs);

                //读取当前的所有数据
                string str_line = sr.ReadLine();  //读取第一行，都是标题，没什么用
                string str_line_prev = "";
                while (str_line != null)
                {
                    str_line_prev = str_line;
                    str_line = sr.ReadLine();  //一直读到最后一行
                }

                //获取最后一行的库存数量
                string[] str_arry = str_line_prev.Split(',');
                Meterial_DATA meterial_DATA = new Meterial_DATA();
                meterial_DATA.NO = Convert.ToInt32(str_arry[0]);                //序号
                meterial_DATA.meterial_No = str_arry[1];                        //物料编号
                meterial_DATA.date = Convert.ToDateTime(str_arry[2]);           //日期
                meterial_DATA.checkin_qty = Convert.ToInt32(str_arry[3]);       //入库数量
                meterial_DATA.checkout_qty = Convert.ToInt32(str_arry[4]);      //出库数量
                meterial_DATA.stock_qty = Convert.ToInt32(str_arry[5]);         //库存

                //list_meterial.Add(meterial_DATA);
                //计算本次入库或出库之后的库存
                //上一次的库存+本次的入库数量-本次的出库数量=本次的库存
                Int32 cur_NO = meterial_DATA.NO + 1;
                Int32 cur_stock_qty = Convert.ToInt32(textBox_checkin_qty.Text) + meterial_DATA.stock_qty - Convert.ToInt32(textBox_checkout_qty.Text); //本次的库存 
                textBox_stock_qty.Text = cur_stock_qty.ToString();

                ////容错
                //if (cur_stock_qty < 0)
                //{
                //    sr.Close();
                //    fs.Close();

                //    MessageBox.Show("库存数量不对");
                //    return;
                //}


                StreamWriter sw = new StreamWriter(fs);
                str_line = cur_NO.ToString()+"," + this.textBox_meterial_No.Text + "," + dateTimePicker_date.Text + "," + textBox_checkin_qty.Text + "," + textBox_checkout_qty.Text + "," + cur_stock_qty.ToString();
                sw.WriteLine(str_line);

                sw.Close();
                sr.Close();
                fs.Close();

                dateTimePicker_date.CustomFormat = "yyyy/MM/dd HH:mm:ss";
                string log = dateTimePicker_date.Text + "  " + textBox_meterial_No.Text + "  " + "入库:" + textBox_checkin_qty.Text + "  " + "出库:" + textBox_checkout_qty.Text + "  " + "库存:" + this.textBox_stock_qty.Text + "\r\n";
                this.richTextBox_log.Text += log;
                m_log += log;
            }
            else
            {
                FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(fs);

                string str_line = "序号," + "物料编号," + "操作时间," + "入库数量," + "出库数量," + "库存";
                sw.WriteLine(str_line);

                //第一次入库的物料，根据入库数量和出库数量，计算出库存
                Int32 stock_qty = Convert.ToInt32(textBox_checkin_qty.Text) - Convert.ToInt32(textBox_checkout_qty.Text);
                this.textBox_stock_qty.Text = stock_qty.ToString();

                str_line = "1," + this.textBox_meterial_No.Text + "," + dateTimePicker_date.Text + "," + textBox_checkin_qty.Text + "," + textBox_checkout_qty.Text + "," + stock_qty.ToString();
                sw.WriteLine(str_line);

                dateTimePicker_date.CustomFormat = "yyyy/MM/dd HH:mm:ss";
                string log = dateTimePicker_date.Text + "  " + textBox_meterial_No.Text + "  " + "入库:" + textBox_checkin_qty.Text + "  " + "出库:" + textBox_checkout_qty.Text + "  " + "库存:" + this.textBox_stock_qty.Text + "\r\n";
                this.richTextBox_log.Text += log;
                m_log += log;

                sw.Close();
                fs.Close();
            }
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.dateTimePicker_date.Text = DateTime.Now.ToString();

        }

        private void textBox_checkin_qty_KeyPress(object sender, KeyPressEventArgs e)
        {
            //8-退格键
            //if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == 8) || e.KeyChar == '.' || e.KeyChar == '-')
            if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == 8) )
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void textBox_checkout_qty_KeyPress(object sender, KeyPressEventArgs e)
        {
            //8-退格键
            //if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == 8) || e.KeyChar == '.' || e.KeyChar == '-')
            if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == 8))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
    }
}
